package com.fingard.dsp.bank.directbank.fuiou01;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import com.fingard.constant.Format;
import com.fingard.crypto.DigestHelper;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.bankInterface.IQryRefund;
import com.fingard.dsp.bank.reqrespobj.qryrefund.ReqQryRefund;
import com.fingard.dsp.bank.reqrespobj.qryrefund.RetAtsQryRefund;
import com.fingard.dsp.bank.reqrespobj.qryrefund.detail.RetAtsRefundDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * 富友退票查询
 * 
 * @author Cruise
 * @date 2019/4/29
 */
public class FUIOU01QryRefund extends FUIOU01Base implements IQryRefund {
	@Override
	public RetAtsQryRefund d_qry_refund(ReqQryRefund p_req) throws Exception {
		RetAtsQryRefund retAts = new RetAtsQryRefund(p_req.reqHeader);
        retAts.writeStart();

        String tmpRespCode = "";
        String tmpRespInfo = "";
        
        int tmpSuccCount = 0;
        double tmpTotalAmt = 0;

        try {
        	ActSetItem actItem = getBankConfig().getActSetItem(p_req.payAct, "");
			if (actItem != null) {
				Calendar tmpCalendarFrom = Calendar.getInstance();
	            tmpCalendarFrom.setTime(p_req.getQryStartDate());

	            Calendar tmpCalendarTo = Calendar.getInstance();
	            tmpCalendarTo.setTime(p_req.getQryEndDate());
	            tmpCalendarTo.add(Calendar.DAY_OF_MONTH, 1);
	            
	            while (tmpCalendarFrom.compareTo(tmpCalendarTo) == -1) {
	            	FUIOU01Header bankHeader = new FUIOU01Header();
					bankHeader.reqtype = "qrytransreq";

					Map<String, String> postParams = new HashMap<String, String>();
					postParams.put("merid", actItem.merchantId);
					postParams.put("reqtype", bankHeader.reqtype);

					XmlTextWriter xmlWriter = new XmlTextWriter();
					xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"" + getCharset() + "\" standalone=\"yes\"?>");
					xmlWriter.writeStartElement("qrytransreq");
					xmlWriter.writeElementString("ver", "1.1");
					xmlWriter.writeElementString("busicd", "AP01");
					xmlWriter.writeElementString("orderno", "");
					xmlWriter.writeElementString("startdt", Format.Date8Format.format(tmpCalendarFrom.getTime()));
					xmlWriter.writeElementString("enddt", Format.Date8Format.format(tmpCalendarFrom.getTime()));
					xmlWriter.writeElementString("transst", "");
					xmlWriter.writeElementString("srcModuleCd", "HMP");
					xmlWriter.writeEndElement();
					xmlWriter.writeEndDocument();

					String reqStr = actItem.merchantId + "|" + actItem.saltKey + "|" + bankHeader.reqtype + "|" + xmlWriter.toXmlString(); 
					String mac = DigestHelper.cryptoMD5RetHexStr(reqStr.getBytes(getCharset()));

					postParams.put("xml", xmlWriter.toXmlString());
					postParams.put("mac", mac);

					String sleepTime = getBankConfig().getValueAsString("qrySleepTime");
					if (StringHelper.hasAnyChar(sleepTime)) {
						Thread.sleep(Long.parseLong(sleepTime) * 1000);
					}
					
					String[] tmpStrRet = sendToBank("generalPay", postParams);
//					String[] tmpStrRet = new String[]{"","<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><qrytransrsp><ret>000000</ret><memo>成功</memo><trans><merdt>20190425</merdt><orderno>29042502913926</orderno><accntno>6214866559910328</accntno><accntnm>张张</accntnm><amt>10</amt><entseq>29042502913926</entseq><memo>代付江西赔款（测）</memo><state>1</state><result>渠道资金到账已复核,交易已发送</result><reason>输入的账号无效，请确认后输入[619X1020114]</reason><tpst>1</tpst><rspcd>999998</rspcd><transStatusDesc>channelFail</transStatusDesc></trans><trans><merdt>20190425</merdt><orderno>29042502917657</orderno><accntno>818580969610001</accntno><accntnm>华安财产保险股份有限公司</accntnm><amt>3000</amt><entseq>29042502917657</entseq><memo>内转</memo><state>1</state><result>渠道资金到账已复核,交易已发送</result><reason>交易成功</reason><tpst>0</tpst><rspcd>000000</rspcd><transStatusDesc>success</transStatusDesc></trans><trans><merdt>20190425</merdt><orderno>29042502917658</orderno><accntno>41000400040014526</accntno><accntnm>华安财产保险股份有限公司</accntnm><amt>2000</amt><entseq>29042502917658</entseq><memo>内转</memo><state>1</state><result>渠道资金到账已复核,交易已发送</result><reason>交易成功</reason><tpst>0</tpst><rspcd>000000</rspcd><transStatusDesc>chanAcceptSuccess</transStatusDesc></trans></qrytransrsp>"};

	                if (tmpStrRet[0].length() == 0) {
	                    StringBuilder tmpSbMsg = new StringBuilder();
	                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);

	                    if (tmpBkReader != null) {
	                    	String tmpRetCode = tmpBkReader.getFirstText("/qrytransrsp/ret");
							String tmpRetInfo = tmpBkReader.getFirstText("/qrytransrsp/memo");
							if (tmpRetCode.equals("000000")) {
								while (tmpBkReader.read("/qrytransrsp/trans")) {
									String isRefunded = tmpBkReader.readedXElement.getSingleText("tpst");
									if ("1".equals(isRefunded)) {
										RetAtsRefundDetail tmpRetDetail = new RetAtsRefundDetail();
		                                tmpRetDetail.askNum = tmpBkReader.readedXElement.getSingleText("orderno");
		                                tmpRetDetail.payAct = p_req.payAct;
		                                tmpRetDetail.payActName = p_req.payActName;
		                                tmpRetDetail.recAct = tmpBkReader.readedXElement.getSingleText("accntno");
		                                tmpRetDetail.recActName = tmpBkReader.readedXElement.getSingleText("accntnm");
		                                tmpRetDetail.amount = StringHelper.amountDivide100(tmpBkReader.readedXElement.getSingleText("amt"));
		                                tmpRetDetail.refundTicketDate = Format.Date10Format.format(tmpCalendarFrom.getTime());
		                                tmpRetDetail.submitTime = Format.DateTimeFormat.format(tmpCalendarFrom.getTime());
		                                
		                                tmpRetInfo = tmpBkReader.readedXElement.getSingleText("reason");
		                                if (StringHelper.hasAnyChar(tmpRetInfo)) {
		    								tmpRespInfo = tmpRetInfo;
		    								if (StringHelper.isNullOrEmpty(tmpRetInfo)) {
		    									tmpRetInfo = tmpBkReader.readedXElement.getSingleText("result");
			    								if (StringHelper.hasAnyChar(tmpRetInfo)) {
			    									tmpRespInfo = tmpRetInfo;
			    								}
		    								}
		    							}
		                                tmpRetDetail.refundTicketReason = tmpRespInfo;
		                                tmpRetDetail.memo = tmpRespInfo;

		                                tmpSuccCount++;
		                                tmpTotalAmt += Double.parseDouble(tmpRetDetail.amount);

		                                retAts.writeRetDetail(tmpRetDetail);
									}
	                            }
							} else {
								tmpRespCode = "-1";
								tmpRespInfo = tmpRetInfo;
							}
	                    } else {
	                        tmpRespCode = "-1";
	                        tmpRespInfo = tmpSbMsg.toString();
	                    }
	                } else {
	                    tmpRespCode = "-1";
	                    tmpRespInfo = tmpStrRet[1];
	                }
	                
	                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
	            }
	            
	            retAts.totleAmount = String.valueOf(tmpTotalAmt);
	            retAts.totleNum = String.valueOf(tmpSuccCount);
			} else {
                tmpRespCode = "-1";
				tmpRespInfo = "未找到账号[" + p_req.payAct + "]商户配置信息!";
			}
        } catch (Exception ex) {
        	ex.printStackTrace();
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        if ("-1".equals(tmpRespCode)) {
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("当前时间范围内无退票数据!");
        }

        retAts.writeEnd();
        return retAts;
	}
}
